package com.xebest.util.seq;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Random;

/**
 * 采购中心序列号生成规则类
 *
 * @author 李贝贝
 */
@Component
public class PurchSeqUtil {

    public static PurchSeqUtil seqUtils = null;

    @Autowired
    protected RedisTemplate<String, String> redisTemplate;

    @PostConstruct
    public void init() {
        seqUtils = this;
    }

    /**
     * 根据seqName 查询自增长值 每次增长为1
     *
     * @param seqName  seqName
     * @param startNum 起始值 只有第一次生效
     */
    public String getNextSeq(String seqName, String startNum) {

        ValueOperations<String, String> redis = redisTemplate.opsForValue();
        Boolean isOk = redisTemplate.hasKey(seqName);

        Long val = null;
        if (isOk) {
            val = redis.increment(seqName, 1);
            return val.toString();
        } else {
            if (StringUtils.isBlank(startNum)) {
                startNum = "1";
            }
            redis.set(seqName, startNum);
            return startNum;
        }
    }

    private String getDateStr() {
        Calendar now = Calendar.getInstance();
        //获得6为日期
        String y = String.valueOf(now.get(Calendar.YEAR)).substring(2, 4);
        String m = String.valueOf(now.get(Calendar.MONTH) + 1);
        String d = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
        m = m.length() > 1 ? m : "0" + m;
        d = m.length() > 1 ? d : "0" + d;
        return y + m + d;
    }

    private int getRandom(int min, int max) {
        Random random = new Random();
        int randNumber = random.nextInt(max - min) + min;
        return randNumber;
    }

    /**
     * 重新初始化seq
     */
    private String getOrSetKeyNextSeq(String seqName, String startNum) {
        ValueOperations<String, String> redis = redisTemplate.opsForValue();
        Long val = null;
        Boolean isOk = redisTemplate.hasKey(seqName);
        if (!isOk || StringUtils.isBlank(startNum)) {
            if (StringUtils.isBlank(startNum)) {
                startNum = "1";
            }
            redis.set(seqName, startNum);
            return startNum;
        } else {
            val = redis.increment(seqName, 1);
            return val.toString();
        }
    }

    private String getLastNum(String seqName) {
        String lastNum;
        String seqNumStr = getNextSeq(seqName, "1");
        int seqNum = Integer.parseInt(seqNumStr);
        //当自增数大于9999重置为1开始
        if (seqNum > 9999) {
            seqNumStr = getOrSetKeyNextSeq(seqName, null);
        }
        //计算当前自增数量需要补全的前缀字符
        int len = 4 - seqNumStr.length();
        //补全前缀
        StringBuilder prefixStr = new StringBuilder("");
        if (len > 0) {
            for (int i = 0; i < len; i++) {
                prefixStr.append("0");
            }
        }
        //格式化
        lastNum = prefixStr.toString() + seqNumStr;
        return lastNum;
    }

    private String getThreeNum(String seqName) {
        String threeNum;
        String seqNumStr = getNextSeq(seqName, "1");
        int seqNum = Integer.parseInt(seqNumStr);
        //当自增数大于9999重置为1开始
        if (seqNum > 999) {
            seqNumStr = getOrSetKeyNextSeq(seqName, null);
        }
        //计算当前自增数量需要补全的前缀字符
        int len = 3 - seqNumStr.length();
        //补全前缀
        StringBuilder prefixStr = new StringBuilder("");
        if (len > 0) {
            for (int i = 0; i < len; i++) {
                prefixStr.append("0");
            }
        }
        //格式化
        threeNum = prefixStr.toString() + seqNumStr;
        return threeNum;
    }


    /**
     * 采购信息  采购单号序列号生成
     * 生成规则：CG+6位年月日+4位随机数+4位流水号
     *
     * @author wangyp
     */
    public String createPurchOrder() {
        StringBuilder purchOrder = new StringBuilder("CG");
        //6位年月日
        purchOrder.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        purchOrder.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_PURCH_ORDER_PURCHORDER);
        purchOrder.append(lastStr);
        return purchOrder.toString();
    }

    /**
     * 供货商信息 供货商编码序列号生成
     * 生成规则：GHS+6位年月日+4位随机数+4位流水号
     *
     * @author wangyp
     */
    public String createSupplierCode() {
        StringBuilder SupplierCode = new StringBuilder("GHS");
        //6位年月日
        SupplierCode.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        SupplierCode.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_PURCHSUP__SUPPLIER_CODE);
        SupplierCode.append(lastStr);
        return SupplierCode.toString();
    }

    /**
     * 采购供货商联系人  联系人编码序列号生成
     * 生成规则：LXR+6位年月日（添加当天日期）+4位序列号
     *
     * @author wangyp
     */
    public String createLinkmanCode() {
        StringBuilder linkmanCode = new StringBuilder("LXR");
        //6位年月日
        linkmanCode.append(this.getDateStr());
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_SUPLINKMAN_LINKMAN_CODE);
        linkmanCode.append(lastStr);
        return linkmanCode.toString();
    }

    /**
     * 采购供货银行  银行code序列号生成
     * 生成规则：XH+6位年月日（添加当天日期）+4位序列号
     *
     * @author wangyp
     */
    public String createBankCode() {
        StringBuilder bankCode = new StringBuilder("XH");
        //6位年月日
        bankCode.append(this.getDateStr());
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_SUPBANK_BANK_CODE);
        bankCode.append(lastStr);
        return bankCode.toString();
    }

    /**
     * 采购供货商合同 合同code序列号生成
     * 生成规则：HT+6位年月日（添加当天日期）+4位序列号
     *
     * @author wangyp
     */
    public String createContractCode() {
        StringBuilder contractCode = new StringBuilder("HT");
        //6位年月日
        contractCode.append(this.getDateStr());
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_SUPCONTRACT_CONTRACT_CODE);
        contractCode.append(lastStr);
        return contractCode.toString();
    }

    /**
     * 采购供货商合同 合同文件编号序列号生成
     * 生成规则：合同code+三位序列号
     *
     * @param ontractCode 合同编号
     * @author wangyp
     */
    public String createFileCode(String ontractCode) {
        StringBuilder fileCode = new StringBuilder();
        //合同code
        fileCode.append(ontractCode);
        //3位序列号
        String getLastNums = this.getThreeNum(XeVenSeqContents.ERP_SUPAPTITUDE_FILE_CODE);
        fileCode.append(getLastNums);
        return fileCode.toString();
    }


    /**
     * 采购供货商资质 资质code序列号生成
     * 生成规则：ZZ+6位年月日（添加当天日期）+4位序列号
     *
     * @author wangyp
     */
    public String createAptitudeCode() {
        StringBuilder aptitudeCode = new StringBuilder("ZZ");
        //6位年月日
        aptitudeCode.append(this.getDateStr());
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_SUPAPTITUDE_APTITUDE_CODE);
        aptitudeCode.append(lastStr);
        return aptitudeCode.toString();
    }

    /**
     * 询价单 询价单编号序列号生成
     * 生成规则：XJ+6位年月日（添加当天日期）+4位序列号
     *
     * @author wangyp
     */
    public String createInquirysheetCode() {
        StringBuilder inquirysheetCode = new StringBuilder("XJ");
        //6位年月日
        inquirysheetCode.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        inquirysheetCode.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_INQUIRYSHEET_INQUIRY_CODE);
        inquirysheetCode.append(lastStr);
        return inquirysheetCode.toString();
    }

    /**
     * 退货单 退货单编号序列号生成
     * 生成规则：TH+6位年月日（添加当天日期）+4位序列号
     *
     * @author wangyp
     */
    public String createAfterSaleCode() {
        StringBuilder afterSaleCode = new StringBuilder("TH");
        //6位年月日
        afterSaleCode.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        afterSaleCode.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_AFTERSALE_SALES_CODE);
        afterSaleCode.append(lastStr);
        return afterSaleCode.toString();
    }

    /**
     * 采购单报关单
     * 生成规则：TH+6位年月日（添加当天日期）+4位序列号
     *
     * @author Wangyp
     */
    public String createBgdCode() {
        StringBuilder afterSaleCode = new StringBuilder("TH");
        //6位年月日
        afterSaleCode.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        afterSaleCode.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_ORDER_BGD_CODE);
        afterSaleCode.append(lastStr);
        return afterSaleCode.toString();
    }

    /**
     * 采购检疫证
     * 生成规则：TH+6位年月日（添加当天日期）+4位序列号
     *
     * @author Wangyp
     */
    public String createJyzCode() {
        StringBuilder afterSaleCode = new StringBuilder("TH");
        //6位年月日
        afterSaleCode.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        afterSaleCode.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_ORDER_JYZ_CODE);
        afterSaleCode.append(lastStr);
        return afterSaleCode.toString();
    }

    /**
     * 采购合同
     * 生成规则：TH+6位年月日（添加当天日期）+4位序列号
     *
     * @author Wangyp
     */
    public String createHtCode() {
        StringBuilder afterSaleCode = new StringBuilder("TH");
        //6位年月日
        afterSaleCode.append(this.getDateStr());
        //获得四位随机数
        int randNumber = this.getRandom(1000, 10000);
        afterSaleCode.append(randNumber);
        //获得4位增长数
        String lastStr = this.getLastNum(XeVenSeqContents.ERP_ORDER_HT_CODE);
        afterSaleCode.append(lastStr);
        return afterSaleCode.toString();
    }


}
